import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'store_state.dart';
import '../../data/repositories/api_repository.dart';
import '../../data/models/product_model.dart';
import '../../data/models/product_category_model.dart';
import '../auth/auth_logic.dart';

/// 商店逻辑控制器 - Store Logic Controller
/// 
/// 负责商店页面的业务逻辑处理，包括商品分类、商品列表、购买流程等
/// Handles store page business logic including product categories, product lists, purchase flow, etc.
/// 
/// 严格遵循网络数据加载规范，所有商品数据必须从后端API获取
/// Strictly follows network data loading specifications, all product data must be fetched from backend APIs
/// 
/// 基于GetX最新最佳实践实现，提供响应式状态管理
/// Based on GetX latest best practices, providing reactive state management
class StoreLogic extends GetxController {
  /// 状态管理 - State management
  final state = Rx<StoreState>(StoreState());
  
  /// API仓库实例 - API repository instance
  final ApiRepository _apiRepository = ApiRepository();

  @override
  void onInit() {
    super.onInit();
    // 初始化状态 - Initialize state
    _initializeState();
  }

  @override
  void onReady() {
    super.onReady();
    // 页面准备完成后加载数据 - Load data after page is ready
    loadStoreData();
  }

  /// 初始化状态 - Initialize state
  /// 设置初始状态值，为数据加载做准备
  /// Sets initial state values, prepares for data loading
  void _initializeState() {
    state.value = StoreState();
  }

  /// 加载商店数据 - Load store data
  /// 并行加载商品分类和推荐商品，提高页面加载速度
  /// Loads product categories and featured products in parallel to improve page loading speed
  Future<void> loadStoreData() async {
    try {
      state.value.isLoading = true;
      state.value.errorMessage = null;

      // 并行加载分类和推荐商品 - Load categories and featured products in parallel
      final results = await Future.wait([
        _loadCategories(), // 加载商品分类 - Load product categories
        _loadFeaturedProducts(), // 加载推荐商品 - Load featured products
      ]);

      // 检查加载结果 - Check loading results
      bool categoriesSuccess = results[0] as bool;
      bool featuredSuccess = results[1] as bool;

      if (categoriesSuccess && featuredSuccess) {
        state.value.isLoading = false;
        
        // 如果有分类数据，默认选择第一个分类并加载其商品
        // If there are categories, select the first one by default and load its products
        if (state.value.categories.isNotEmpty) {
          await selectCategory(state.value.categories.first);
        }
      } else {
        throw Exception('部分数据加载失败');
      }
    } catch (e) {
      print('加载商店数据失败: $e');
      state.value.isLoading = false;
      state.value.errorMessage = '加载失败: $e';
    }
  }

  /// 加载商品分类 - Load product categories
  /// 从后端API获取所有可用的商品分类
  /// Fetches all available product categories from backend API
  Future<bool> _loadCategories() async {
    try {
      // 调用API获取分类数据 - Call API to get category data
      final result = await _apiRepository.getProductCategories();
      
      if (result.success && result.data != null) {
        final categories = (result.data as List)
            .map((json) => ProductCategory.fromJson(json))
            .where((category) => category.isActive) // 只显示激活的分类 - Only show active categories
            .toList();
        
        // 按排序字段排序 - Sort by sort order
        categories.sort((a, b) => a.sortOrder.compareTo(b.sortOrder));
        
        state.value.categories = categories.map((c) => c.name).toList();
        
        print('商品分类加载成功，共${categories.length}个分类');
        return true;
      } else {
        throw Exception('分类数据格式错误');
      }
    } catch (e) {
      print('加载商品分类失败: $e');
      return false;
    }
  }

  /// 加载推荐商品 - Load featured products
  /// 获取首页推荐的热门商品
  /// Gets featured products recommended for homepage
  Future<bool> _loadFeaturedProducts() async {
    try {
      // 调用API获取推荐商品 - Call API to get featured products
      final result = await _apiRepository.getFeaturedProducts();
      
      if (result.success && result.data != null) {
        final featuredProducts = (result.data as List)
            .map((json) => Product.fromJson(json))
            .where((product) => product.isAvailable) // 只显示可用商品 - Only show available products
            .toList();
        
        state.value.featured = featuredProducts.map((p) => p.name).toList();
        
        print('推荐商品加载成功，共${featuredProducts.length}个商品');
        return true;
      } else {
        throw Exception('推荐商品数据格式错误');
      }
    } catch (e) {
      print('加载推荐商品失败: $e');
      return false;
    }
  }

  /// 选择商品分类 - Select product category
  /// 切换分类时加载对应的商品列表
  /// Loads corresponding product list when switching categories
  Future<void> selectCategory(String categoryId) async {
    if (state.value.selectedCategoryId == categoryId) {
      return; // 如果是同一个分类，不重复加载 - Don't reload if it's the same category
    }

    try {
      state.value.errorMessage = null;
      state.value.selectedCategoryId = categoryId;
      state.value.isLoadingProducts = true;

      // 调用API获取分类商品 - Call API to get category products
      final result = await _apiRepository.getProductsByCategory(categoryId);
      
      if (result.success && result.data != null) {
        final products = (result.data as List)
            .map((json) => Product.fromJson(json))
            .where((product) => product.isAvailable) // 只显示可用商品 - Only show available products
            .toList();
        
        // 按价格排序 - Sort by price
        products.sort((a, b) => a.price.compareTo(b.price));
        
        state.value.featured = products.map((p) => p.name).toList();
        state.value.isLoadingProducts = false;
        
        print('分类商品加载成功，共${products.length}个商品');
      } else {
        throw Exception('分类商品数据格式错误');
      }
    } catch (e) {
      print('加载分类商品失败: $e');
      state.value.errorMessage = '加载分类商品失败: $e';
      state.value.isLoadingProducts = false;
    }
  }

  /// 刷新商店数据 - Refresh store data
  /// 下拉刷新时调用，重新加载所有数据
  /// Called on pull-to-refresh, reloads all data
  Future<void> refreshStoreData() async {
    state.value.isRefreshing = true;
    
    await loadStoreData();
    
    state.value.isRefreshing = false;
  }

  /// 购买商品 - Purchase product
  /// 处理商品购买流程
  /// Handles product purchase flow
  Future<void> purchaseProduct(String productId) async {
    try {
      // 检查用户登录状态 - Check user login status
      final authLogic = Get.find<AuthLogic>();
      if (!authLogic.state.value.isLoggedIn) {
        Get.snackbar(
          '提示',
          '请先登录后再购买商品',
          snackPosition: SnackPosition.TOP,
          backgroundColor: Colors.orange,
          colorText: Colors.white,
        );
        return;
      }

      // 调用购买API - Call purchase API
      final result = await _apiRepository.purchaseProduct(productId);
      
      if (result.success) {
        Get.snackbar(
          '购买成功',
          '商品购买成功，请查看订单详情',
          snackPosition: SnackPosition.TOP,
          backgroundColor: Colors.green,
          colorText: Colors.white,
        );
      } else {
        throw Exception(result.message ?? '购买失败');
      }
    } catch (e) {
      print('购买商品失败: $e');
      Get.snackbar(
        '购买失败',
        '购买商品失败: $e',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.red,
        colorText: Colors.white,
      );
    }
  }

  /// 搜索商品 - Search products
  /// 根据关键词搜索商品
  /// Search products by keywords
  Future<void> searchProducts(String keyword) async {
    if (keyword.trim().isEmpty) {
      return;
    }

    try {
      state.value.isLoading = true;
      state.value.errorMessage = null;
      state.value.selectedCategoryId = '';

      // 调用搜索API - Call search API
      final result = await _apiRepository.searchProducts(keyword);
      
      if (result.success && result.data != null) {
        final products = (result.data as List)
            .map((json) => Product.fromJson(json))
            .where((product) => product.isAvailable) // 只显示可用商品 - Only show available products
            .toList();
        
        state.value.isLoading = false;
        state.value.featured = products.map((p) => p.name).toList();
        
        print('搜索商品成功，共找到${products.length}个商品');
      } else {
        throw Exception('搜索结果为空');
      }
    } catch (e) {
      print('搜索商品失败: $e');
      state.value.isLoading = false;
      state.value.errorMessage = '搜索失败: $e';
    }
  }

  /// 清除错误信息 - Clear error message
  /// 清除当前的错误信息
  /// Clears current error message
  void clearError() {
    state.value.errorMessage = null;
  }
}
